package com.sl.au.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sl.au.entity.ScadaBasePointScadaRtuBase;
import com.sl.au.entity.User;
import com.sl.au.entity.scadaModelBaseInfo;
import com.sl.au.entity.scadaModelPointRelation;
import com.sl.au.repository.ExdeScadaModelBaseInfoRepository;
import com.sl.au.repository.ScadaBasePointScadaRtuBaseRepository;
import com.sl.au.repository.scadaModelPointRelatioRepository;
import com.sl.au.service.ExdeScadaModelBaseInfoService;
import com.sl.au.service.QueryService;

@Service("ExdeScadaModelBaseInfoService")
@Transactional
public class ExdeScadaModelBaseInfoServiceImpl extends BaseServiceImpl implements ExdeScadaModelBaseInfoService {

	@Autowired
	ExdeScadaModelBaseInfoRepository exdeScadaModelBaseInfoRepository;
	
	@Autowired
	ScadaBasePointScadaRtuBaseRepository scadaBasePointScadaRtuBaseRepository;
	
	@Autowired
	scadaModelPointRelatioRepository scadamodelPointRelatioRepository;
	
	@Autowired
	QueryService queryService;
	
	@Override
	public ExdeScadaModelBaseInfoRepository getExdeScadaModelBaseInfoRepository() {
		return this.exdeScadaModelBaseInfoRepository;
	}
	
	@Override
	public ScadaBasePointScadaRtuBaseRepository getScadaBasePointScadaRtuBaseRepository() {
		return this.scadaBasePointScadaRtuBaseRepository;
	}
	
	@Override
	public List<scadaModelBaseInfo> getscadaModelBaseInfos(int start, int length, Map<String, String> condition, User user,  String orderName, String dir) {
		Page<scadaModelBaseInfo> pages = null;
		String dataFilter = condition.get("dataFilter");
		Pageable pageable = new PageRequest(start / length, length, Sort.Direction.DESC, "createTime");
		if(dataFilter.equals("所有")){
			pages = exdeScadaModelBaseInfoRepository.getscadaModelBaseInfos(condition.get("key"), pageable);
		}else if(dataFilter.equals("本部门")){
			pages = exdeScadaModelBaseInfoRepository.getscadaModelBaseInfos(condition.get("key"), condition.get("superior"), pageable);
		}else if(dataFilter.equals("本片区")){
			pages = exdeScadaModelBaseInfoRepository.getscadaModelBaseInfos(condition.get("key"), condition.get("superior"), condition.get("areaName"),  pageable);
		}else if(dataFilter.equals("本人")){
			pages = exdeScadaModelBaseInfoRepository.getscadaModelBaseInfosByUser(condition.get("key"), condition.get("userId"), pageable);
		}
		return pages.getContent();
	}

	@Override
	public long getscadaModelBaseInfosCount(int i, int maxValue, Map<String, String> condition, User user, String orderName, String dir) {
		String dataFilter = condition.get("dataFilter");
		if(dataFilter.equals("所有")){
			return this.exdeScadaModelBaseInfoRepository.getscadaModelBaseInfosCount(condition.get("key"));
		}else if(dataFilter.equals("本部门")){
			return this.exdeScadaModelBaseInfoRepository.getscadaModelBaseInfosCount(condition.get("key"), condition.get("superior"));
		}else if(dataFilter.equals("本片区")){
			return this.exdeScadaModelBaseInfoRepository.getscadaModelBaseInfosCount(condition.get("key"), condition.get("superior"), condition.get("areaName"));
		}else{
			return this.exdeScadaModelBaseInfoRepository.getscadaModelBaseInfosByUserCount(condition.get("key"), condition.get("userId"));
		}
	}

	//加载树
	@Override
	public List<Map<String, Object>> getNodeMap(String id) {
		List<Map<String, Object>> nodeMap = new ArrayList<Map<String, Object>>();
		//List<scadaModelBaseInfo> RootNodes = exdeScadaModelBaseInfoRepository.getRootNodes();
		scadaModelBaseInfo RootNode = exdeScadaModelBaseInfoRepository.findOne(id);
		//for(scadaModelBaseInfo RootNode : RootNodes){//所有节点
		if(null != RootNode && RootNode.getUpParaId()==null){
			Map<String, Object> map = new HashMap<String, Object>();
			List<Map<String, Object>> childrenMap = new ArrayList<Map<String, Object>>();
			childrenMap = findChildren(RootNode);
			if(childrenMap != null){
				map.put("isParent", true);
				map.put("open",true);
				map.put("children",childrenMap);
			} else {
				map.put("isParent", false);
				map.put("open",false);
			}
			map.put("name",RootNode.getModelName());
			map.put("id",RootNode.getId());
			map.put("memo",RootNode.getMemo());
			map.put("parentId",0);
			nodeMap.add(map);
		}
		//}
		return nodeMap;
	}

	/**
	 * 加载树的递归方法
	 * @param scadamodelBaseInfo
	 * @return
	 */
	public List<Map<String, Object>> findChildren(scadaModelBaseInfo scadamodelBaseInfo) {
		List<Map<String, Object>> childrenMap = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> childrenMap1 = new ArrayList<Map<String, Object>>();
		List<scadaModelBaseInfo> detailType=new ArrayList<>();
		detailType=exdeScadaModelBaseInfoRepository.findByupParaId(scadamodelBaseInfo.getId());//
		if(detailType.size()>0) {
			for (scadaModelBaseInfo d : detailType) {
				List<scadaModelBaseInfo> detailType1=new ArrayList<>();
				Map<String, Object> map1 = new HashMap<String, Object>();
				detailType1 = exdeScadaModelBaseInfoRepository.findByupParaId(d.getId());
				Map<String, Object> map = new HashMap<String, Object>();
				if(detailType1.size()>0){
					childrenMap1 = findChildren(d);
					map1.put("name", d.getModelName());
					map1.put("id",d.getId());
					map1.put("memo", d.getMemo());
					map1.put("parentId", scadamodelBaseInfo.getId());
					map1.put("father",scadamodelBaseInfo.getModelName());
					map1.put("isParent", true);
					map1.put("open",true);
					map1.put("children",childrenMap1);
					childrenMap.add(map1);
				}else{
					map1.put("name", d.getModelName());
					map1.put("id",d.getId());
					map1.put("memo", d.getMemo());
					map1.put("parentId", scadamodelBaseInfo.getId());
					map1.put("father",scadamodelBaseInfo.getModelName());
					childrenMap.add(map1);
				}
			}
		}
		return childrenMap;
	}
	

	/**
	 * 点位表的加载
	 */
	@Override
	public List<ScadaBasePointScadaRtuBase> getScadaBasePointScadaRtuBases(int start, int length,
			Map<String, String> condition, User user, String orderName, String dir) {
		@SuppressWarnings("unchecked")
		String dataFilter = condition.get("dataFilter");
		String key = condition.get("key");
		String superior = condition.get("superior");
		String areaName = condition.get("areaName");
		String userId = condition.get("userId");
		String pointType = condition.get("pointType");
		String Type = condition.get("Type");
		String id = condition.get("id");
		
		Map<String,Object>namedParamsMap=new HashMap<String,Object>();
		StringBuilder hql = new StringBuilder();
		hql.append("select e from ScadaBasePointScadaRtuBase e where (e.id is not null) and (e.pointType like '%" + pointType.toString() + "%' )");
		
		if(Type.toString().equals("未引入")){
			hql.append(" and (e.modelId is null) ");
		}else{
			hql.append(" and (e.modelId = '"+id.toString()+"') ");
		}
		if(!key.toString().equals("")){
			hql.append(" and (e.scadaRtuBaseInfoName like '%"+key.toString()+"%' or e.name like '%"+key.toString()+"%'"
					+ " or e.alias like '%"+key.toString()+"%' or e.dataField like '%"+key.toString()+"%' ) ");
		}
		
		if(dataFilter.equals("所有")){
			hql.append("");
		}else if(dataFilter.equals("本部门")){
			hql.append(" and (e.user.saleArea.superior = '"+superior.toString()+"' ) ");
		}else if(dataFilter.equals("本片区")){
			hql.append(" and (e.user.saleArea.superior = '"+superior.toString()+"' and e.user.saleArea.areaName = '"+areaName.toString()+"' ) ");
		}else if(dataFilter.equals("本人")){
			hql.append(" and (e.user = '"+userId.toString()+"' ) ");
		}
		hql.append(" order by e." + orderName + " " + dir);
		System.out.println(hql.toString());
		Query query=queryService.createQueryHql(hql.toString());
		query.setFirstResult(start).setMaxResults(length);
		return queryService.executeHql(query, namedParamsMap);
	}

	/**
	 * 保存点位与节点关系表
	 */
	@Override
	public void savescadaModelPointRelation(String modelId, String[] pointIds, User user) {
		for(int i=0;i<pointIds.length;i++){
			scadaModelPointRelation scadamodelPointRelation = new scadaModelPointRelation();
			scadamodelPointRelation.setModelId(modelId);
			scadamodelPointRelation.setPointId(pointIds[i]);
			scadamodelPointRelation.setUser(user);
			scadamodelPointRelatioRepository.save(scadamodelPointRelation);
		}
	}

	/**
	 * 删除点位
	 */
	@Override
	public void deletepoint(String pointIds) {
		StringBuilder hql = buildCombinedQueryHql("scadaModelPointRelation", "pointId", pointIds, "createTime", "desc");
		Query query=queryService.createQueryHql(hql.toString());
		System.out.println(hql.toString());
		@SuppressWarnings("unchecked")
		List<scadaModelPointRelation> lists = query.getResultList();
		scadamodelPointRelatioRepository.delete(lists);
	}

	//删除节点
	@Override
	public void deleteNote(String id) {
		String ModelIds = "";
		scadaModelBaseInfo scadamodelBaseInfo = exdeScadaModelBaseInfoRepository.findOne(id);
		if(scadamodelBaseInfo!=null){
			ModelIds += findNote(id);
		}
		ModelIds += "'"+scadamodelBaseInfo.getId()+"'";
		StringBuilder hql = buildCombinedQueryHql("scadaModelBaseInfo", "id", ModelIds, "createTime", "desc");
		Query query=queryService.createQueryHql(hql.toString());
		System.out.println(hql.toString());
		@SuppressWarnings("unchecked")
		List<scadaModelBaseInfo> listAll = query.getResultList();//查找模型
//		List<scadaModelBaseInfo> listAll = exdeScadaModelBaseInfoRepository.findByIds(ModelIds);
		
		StringBuilder hql1 = buildCombinedQueryHql("scadaModelPointRelation", "modelId", ModelIds, "createTime", "desc");
		Query query1=queryService.createQueryHql(hql1.toString());
		System.out.println(hql.toString());
		@SuppressWarnings("unchecked")
		List<scadaModelPointRelation> lists = query1.getResultList();//点位对应模型的关系
		
		scadamodelPointRelatioRepository.delete(lists);
		exdeScadaModelBaseInfoRepository.delete(listAll);
		
	}
	/**
	 * sql in 的查询
	 * @param entityName 类名称
	 * @param selectedProperty 筛选条件字段
	 * @param ids 筛选条件
	 * @param orderName
	 * @param dir
	 * @return
	 */
	public StringBuilder buildCombinedQueryHql(String entityName, String selectedProperty, String ids, String orderName, String dir){
		StringBuilder hql = new StringBuilder();
		hql.append("select e from " + entityName + " e where e.id is not null ");
		hql.append(" and e." + selectedProperty + " in (" + ids + ")");
		hql.append(" order by " + orderName + " " + dir);
		return hql;
	}
	/**
	 * 递归查询出节点下的所有id
	 * @param id
	 * @return
	 */
	public String findNote(String id) {
		String ModelIds = "";
		List<scadaModelBaseInfo> lists = exdeScadaModelBaseInfoRepository.findByupParaId(id);
		if(lists.size()>0){
			for(scadaModelBaseInfo list : lists){
				List<scadaModelBaseInfo> lists1 = exdeScadaModelBaseInfoRepository.findByupParaId(list.getId());
				if(lists1.size()>0)
					ModelIds += findNote(list.getId());
				ModelIds += "'"+list.getId() + "',";
			}
		}
		return ModelIds;
	}

	/**
	 * modelId 新节点的父节点
	 */
	@Override
	public void savescadaModelPoint(String modelId, String pointId, User user) {
		scadaModelBaseInfo father = exdeScadaModelBaseInfoRepository.findOne(modelId);
		scadaModelBaseInfo son = exdeScadaModelBaseInfoRepository.findOne(pointId);
		if(father!=null && son!=null){
			String ModelIds = "";
			scadaModelBaseInfo newSon = new scadaModelBaseInfo();
			newSon.setCreateTime(new Date());
			newSon.setUpParaId(father.getId());
			newSon.setModelName(son.getModelName());
			newSon.setMemo(son.getMemo());
			newSon.setUser(user);
			exdeScadaModelBaseInfoRepository.save(newSon);
			ModelIds += savescadaModel(newSon.getId(), son.getId(), user);
			ModelIds += "'"+son.getId()+"'";
			System.out.println(ModelIds);
		}
	}

	/**
	 * 
	 * @param newId 新的节点的父节点id
	 * @param id 
	 * @param user
	 * @return
	 */
	public String savescadaModel(String newId, String id, User user) {
		String ModelIds = "";
		//scadaModelBaseInfo father = exdeScadaModelBaseInfoRepository.findOne(id);
		List<scadaModelBaseInfo> sons = exdeScadaModelBaseInfoRepository.findByupParaId(id);
		if(sons.size()>0){
			for(scadaModelBaseInfo son : sons){
				List<scadaModelBaseInfo> sons1 = exdeScadaModelBaseInfoRepository.findByupParaId(son.getId());
				scadaModelBaseInfo newSon = new scadaModelBaseInfo();
				newSon.setCreateTime(new Date());
				newSon.setUpParaId(newId);
				newSon.setModelName(son.getModelName());
				newSon.setMemo(son.getMemo());
				newSon.setUser(user);
				exdeScadaModelBaseInfoRepository.save(newSon);
				if(sons1.size()>0)
					ModelIds += savescadaModel(newSon.getId(), son.getId(), user);
				ModelIds += "'"+son.getId()+"',";
			}
		}
		return ModelIds;
	}

	

}
